package com.qms.tubu.fragment.account;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.qms.tubu.R;
import com.qms.tubu.activity.account.RegisterActivity;
import com.qms.tubu.bean.AccountBean;
import com.qms.tubu.fragment.BaseFragment;
import com.qms.tubu.tools.SPHelper;
import com.qms.tubu.tools.UrlConfig;
import com.qms.tubu.widget.LoadLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.UnknownHostException;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import tool.lib.TextFormTool;
import tool.lib.ToastTool;
import tool.lib.volley.ExErrorListener;
import tool.lib.volley.ExListener;
import tool.lib.volley.JsonRequest;
import tool.lib.volley.VolleyTool;

/**
 * Created by Mad on 2015/7/22.
 */
public class RegisterFragment extends BaseFragment implements TextWatcher,View.OnClickListener{
    private EditText mPhoneEdit,mPasswordEdit,mVerityEdit;
    private FrameLayout mVerityBtn,mCommitBtn;
    private TextView mVerityText,mCommitText;
    private LoadLayout mLoad;
    private int liveTime;
    private AccountBean mAccount;
    private Handler mTimeHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            liveTime--;
            if(liveTime>0) {
                mVerityText.setText(liveTime+"秒");
                mTimeHandler.postDelayed(timeRunnable,1000);
            }
            else {
                mVerityText.setText("发送验证码");
                mPhoneEdit.setEnabled(true);
                setVerityBtnEnabled(true);
            }
        }
    };
    private Runnable timeRunnable=new Runnable() {
        @Override
        public void run() {
            mTimeHandler.sendEmptyMessage(0);
        }
    };
    private Handler mainEventHandle=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            int event= msg.arg1;
            int result=msg.arg2;
            Object data=msg.obj;
            if (result == SMSSDK.RESULT_COMPLETE) {
                //回调完成
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    //提交验证码成功
                    requestRegister();
                }else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
                    //获取验证码成功
                    liveTime=90;
                    mVerityText.setText(liveTime+"秒");
                    mTimeHandler.postDelayed(timeRunnable, 1000);
                }
            }else{
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    mLoad.finishLoad();
                }else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
                    mVerityText.setText("发送验证码");
                    mPhoneEdit.setEnabled(true);
                    setVerityBtnEnabled(true);
                }
                if(data instanceof UnknownHostException)
                    ToastTool.showToast("网络无连接,请联网后操作");
                else if(data instanceof  Throwable)
                {
                    try {
                        JSONObject object=new JSONObject(((Throwable) data).getMessage());
                        ToastTool.showToast(object.getString("description"));
                    } catch (JSONException e) {
                        ToastTool.showToast(data.toString());
                    }
                }
                else
                    ToastTool.showToast(data.toString());
            }
        }
    };
    EventHandler eventHandler=new EventHandler(){
        @Override
        public void afterEvent(int event, int result, Object data) {
            Message msg=new Message();
            msg.arg1 = event;
            msg.arg2 = result;
            msg.obj = data;
            mainEventHandle.sendMessage(msg);
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle=getArguments();
        if(bundle!=null)
        {
            mAccount= (AccountBean) bundle.getSerializable("account");
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView=inflater.inflate(R.layout.fragment_register,container,false);
        mPhoneEdit= (EditText) rootView.findViewById(R.id.register_phone_edit);
        mPasswordEdit= (EditText) rootView.findViewById(R.id.register_password_edit);
        mVerityEdit= (EditText) rootView.findViewById(R.id.register_verity_edit);
        mVerityBtn= (FrameLayout) rootView.findViewById(R.id.register_verity_btn);
        mCommitBtn= (FrameLayout) rootView.findViewById(R.id.register_commit_btn);
        mVerityText= (TextView) rootView.findViewById(R.id.register_verity_text);
        mCommitText= (TextView) rootView.findViewById(R.id.register_commit_text);
        mLoad= (LoadLayout) rootView.findViewById(R.id.load_layout);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        SMSSDK.registerEventHandler(eventHandler);
        mPhoneEdit.addTextChangedListener(this);
        mPasswordEdit.addTextChangedListener(this);
        mVerityEdit.addTextChangedListener(this);
        mVerityBtn.setOnClickListener(this);
        mCommitBtn.setOnClickListener(this);
        setVerityBtnEnabled(false);
        setCommitBtnEnabled(false);
    }
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        boolean canCommit=true;
        if(TextFormTool.checkPhoneForm(mPhoneEdit.getText().toString()))
        {
            setVerityBtnEnabled(true);
        }
        else
        {
            canCommit=false;
            setVerityBtnEnabled(false);
        }
        String passwordStr=mPasswordEdit.getText().toString();
        if(passwordStr.length()<6 || passwordStr.length()>16)
            canCommit=false;
        if(mVerityEdit.getText().toString().length()!=4)
            canCommit=false;
        setCommitBtnEnabled(canCommit);
    }
    private void setVerityBtnEnabled(boolean enabled)
    {
        mVerityBtn.setEnabled(enabled);
        mVerityText.setEnabled(enabled);
    }
    private void setCommitBtnEnabled(boolean enabled)
    {
        mCommitText.setEnabled(enabled);
        mCommitBtn.setEnabled(enabled);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.register_verity_btn:
                requestVerityCode();
                break;
            case R.id.register_commit_btn:
                RegisterActivity activity= (RegisterActivity) getActivity();
                activity.hideSoftKeyboard();
                mLoad.startLoad();
                SMSSDK.submitVerificationCode("86", mPhoneEdit.getText().toString(), mVerityEdit.getText().toString());
                break;
        }
    }
    private void requestRegister()
    {
        JsonRequest request=new JsonRequest(UrlConfig.getUrl(R.string.register_register),new ExListener(){
            @Override
            public void onResponse(JSONObject object) {
                super.onResponse(object);
                if(verifyResult.getResult()==0)
                {
                    try {
                        AccountBean account= JSON.parseObject(object.getString("account"),AccountBean.class);
                        account.setLoginType(SPHelper.LOGIN_TYPE_NORMAL);
                        SPHelper.saveAccount(rootView.getContext(),account);
                        getTubuApplication().setAccount(account);
                        getActivity().finish();
                        return;
                    } catch (JSONException e) {
                        verifyResult.setResult(ExListener.PARSE_ERROR);
                    }

                }
                ToastTool.showToast(verifyResult.getMsg());
                mLoad.finishLoad();
            }
        },new ExErrorListener(){
            @Override
            public void onErrorResponse(VolleyError error) {
                super.onErrorResponse(error);
                mLoad.finishLoad();
            }
        });
        request.put("phone",mAccount.getPhone());
        request.put("password",mPasswordEdit.getText().toString());
        request.put("nickname",mAccount.getNickname());
        request.put("sex",String.valueOf(mAccount.getSex()));
        request.put("city",mAccount.getCity());
        request.put("province",mAccount.getProvince());
        request.put("birthday",mAccount.getBirthday());
        request.setTag(RegisterFragment.class);
        VolleyTool.getInstance().add(request);
    }
    private void requestVerityCode()
    {
        mPhoneEdit.setEnabled(false);
        setVerityBtnEnabled(false);
        mVerityText.setText("发送中");
        JsonRequest request=new JsonRequest(UrlConfig.getUrl(R.string.register_get_verity),new ExListener(){
            @Override
            public void onResponse(JSONObject object) {
                super.onResponse(object);
                if(verifyResult.getResult()==0)
                {
                    mAccount.setPhone(mPhoneEdit.getText().toString());
                    SMSSDK.getVerificationCode("86",mPhoneEdit.getText().toString());
                    return;
                }
                ToastTool.showToast(verifyResult.getMsg());
                mVerityText.setText("发送验证码");
                mPhoneEdit.setEnabled(true);
                setVerityBtnEnabled(true);
            }
        },new ExErrorListener(){
            @Override
            public void onErrorResponse(VolleyError error) {
                super.onErrorResponse(error);
                mVerityText.setText("发送验证码");
                mPhoneEdit.setEnabled(true);
                setVerityBtnEnabled(true);
            }
        });
        request.put("phone", mPhoneEdit.getText().toString());
        request.setTag(RegisterFragment.class);
        VolleyTool.getInstance().add(request);
    }

    @Override
    public void onDestroyView() {
        mTimeHandler.removeCallbacks(timeRunnable);
        SMSSDK.unregisterEventHandler(eventHandler);
        VolleyTool.getInstance().getRequestQueue().cancelAll(RegisterFragment.class);
        super.onDestroyView();
    }
}
